<template>
  <div class="v-configuration-comps-right-area">
    <div class="add-group">
      <el-button
        :icon="Plus"
        :disabled="componentConfigurationModel.isModelDisabled"
        @click="addGroup"
      >
        新增分组
      </el-button>
      <el-button
        :icon="Link"
        :disabled="componentConfigurationModel.isModelDisabled"
        @click="citeComponent"
      >
        组件引用
      </el-button>
    </div>
    <div class="group-list-wrap">
      <div
        v-for="(item, index) in componentConfigurationModel.siderbarConfig"
        :key="index"
        :class="[{ active: componentConfigurationModel.selectGroupIndex === index }, 'group-item']"
        @click="changeSelectGrouop(index)"
      >
        <div class="group-item-header">
          <div class="header-left">
            <el-input
              :ref="it => componentConfigurationModel.groupNameInputMap.set(item.id, it)"
              v-model="item.cnName"
              :readonly="!item?.editable"
              @blur="componentConfigurationModel.updateGroupName(item)"
              @keyup.enter="componentConfigurationModel.updateGroupName(item)"
              @dblclick="componentConfigurationModel.setGroupInEdit(item, $event)"
            />
          </div>
          <div class="header-right">
            <div @click="clearCompList(index)">
              <img
                src="statics/icons/app/icon_clear.svg"
                class="_clear-icon"
                style="width: 15px; height: 15px"
                :style="{ cursor: componentConfigurationModel.isModelDisabled ? 'not-allowed' : 'pointer' }"
              />
            </div>
            <Edit
              style="width: 16px; height: 16px; margin-left: 8px; cursor: pointer"
              :style="{ cursor: componentConfigurationModel.isModelDisabled ? 'not-allowed' : 'pointer' }"
              @click="componentConfigurationModel.setGroupInEdit(item, $event)"
            />
            <Delete
              :disabled="componentConfigurationModel.isModelDisabled"
              style="width: 16px; height: 16px; margin-left: 8px; cursor: pointer"
              :style="{ cursor: componentConfigurationModel.isModelDisabled ? 'not-allowed' : 'pointer' }"
              @click.stop="deleteGroup(index)"
            />
            <ArrowUp
              v-if="item?.showComps"
              style="width: 1em; height: 1em; margin-left: 8px; cursor: pointer"
              @click="changeShowComps(index)"
            />
            <ArrowDown
              v-if="!item?.showComps"
              style="width: 1em; height: 1em; margin-left: 8px; cursor: pointer"
              @click="changeShowComps(index)"
            />
          </div>
        </div>
        <div
          v-if="item.showComps"
          class="group-item-children"
        >
          <div
            v-for="(comp, compIndex) in item.children"
            :key="compIndex"
            class="comp-item"
            :style="{ cursor: componentConfigurationModel.isModelDisabled ? 'not-allowed' : 'pointer' }"
            :class="{ active: currentParentIndex === index && currentIndex === compIndex }"
            :draggable="componentConfigurationModel.isModelDisabled ? false : true"
            @dragstart="dragstart(comp, compIndex)"
            @dragenter="dragenter(comp, $event)"
            @dragend="dragend(index)"
            @dragover="dragover($event)"
            @click="handleClickItem(index, compIndex)"
          >
            <img
              class="comp-item-img"
              :src="comp?.icon"
            />
            <div class="comp-item-label">{{ comp?.name }}</div>
            <CircleCloseFilled
              v-if="currentParentIndex === index && currentIndex === compIndex"
              class="delete-icon"
              @click.stop="removeComp(index, compIndex, comp)"
            ></CircleCloseFilled>
            <!--       <el-tooltip v-if="showTips" :content="comp?.name" placement="bottom" effect="light">
              <div class="comp-item-box">
                <img class="comp-item-img" :src="comp?.icon" />
                <div class="comp-item-label">{{ comp?.name }}</div>
              </div>
            </el-tooltip>
            <div v-if="!showTips" class="comp-item-box">
              <img class="comp-item-img" :src="comp?.icon" />
              <div class="comp-item-label">{{ comp?.name }}</div>
            </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from "vue";
import { ArrowUp, ArrowDown, Edit, Plus, Delete, CircleCloseFilled, Link } from "@element-plus/icons";
import { ComponentConfigurationModel } from "./ComponentConfigurationModel";
import { TreeSelectModel } from "../common/TreeSelectModel";
import { getUid, getUniqueName } from "@/util/common";
import ComponentCiteModel from "./ComponentCiteModel.vue";
import { SiderbarGroup } from "@/modules/model/comps/station/graphTabs/graphEditor/DiagramConfig";

const props = defineProps<{
  componentConfigurationModel: ComponentConfigurationModel;
  treeSelectModel: TreeSelectModel;
}>();
// const inputFocus = ref<any>([]);
const currentIndex = ref(-1);
const currentParentIndex = ref(-1);
// const showTips = ref(true);
let dargIndex = ref(-1);
let oldData = null;
let newData = null;

const dragstart = (value, index) => {
  oldData = value;
  dargIndex.value = index;
  currentIndex.value = -1;
  // showTips.value = false;
};
const dragenter = (value, e) => {
  newData = value;
  e.preventDefault();
};

const dragover = e => {
  e.preventDefault();
};

const dragend = (parentIndex: number) => {
  if (oldData !== newData) {
    let oldIndex = props.componentConfigurationModel.siderbarConfig[parentIndex].children.indexOf(oldData);
    let newIndex = props.componentConfigurationModel.siderbarConfig[parentIndex].children.indexOf(newData);

    let newItems = [...props.componentConfigurationModel.siderbarConfig[parentIndex].children];
    newItems.splice(oldIndex, 1);
    newItems.splice(newIndex, 0, oldData);
    props.componentConfigurationModel.siderbarConfig[parentIndex].children = [...newItems];
  }
  dargIndex.value = -1;
  // showTips.value = true;
};

const handleClickItem = (parentIndex, index) => {
  if (props.componentConfigurationModel.isModelDisabled) return;
  if (currentIndex.value === index) {
    currentIndex.value = -1;
  } else {
    currentParentIndex.value = parentIndex;
    currentIndex.value = index;
  }
};

// 新增分组
const addGroup = () => {
  const nameList = props.componentConfigurationModel.siderbarConfig.map(item => item.cnName);
  const newName = getUniqueName(nameList, "默认分组");
  const groupObj = {
    id: getUid(),
    cnName: newName,
    enName: newName,
    editable: false,
    children: [],
    showComps: true
  };

  props.componentConfigurationModel.siderbarConfig.push(groupObj);
  if (props.componentConfigurationModel.siderbarConfig.length === 1) {
    props.componentConfigurationModel.selectGroupIndex = 0;
  }
  // editGroupName(props.componentConfigurationModel.groupList.length - 1);
};

// 组件引用。将已经配置的其它图的分组引用进来作为基础内容
const citeComponent = () => {
  ComponentCiteModel.popup().then(async (res: SiderbarGroup[]) => {
    if (res.length) {
      props.componentConfigurationModel.joinSiderbarConfig(res);
    }
  });
};

const changeShowComps = (index: number) => {
  props.componentConfigurationModel.siderbarConfig[index].showComps = !props.componentConfigurationModel.siderbarConfig[index].showComps;
};

// 编辑分组名称
// const editGroupName = (index: number) => {
//   if (props.componentConfigurationModel.isModelDisabled) return;
//   nextTick(() => {
//     props.componentConfigurationModel.siderbarConfig[index].editable = true;
//     inputFocus.value[index].focus();
//   });
// };

// 清除某个分组下的所有已选组件，也需要讲该分组下在rightSelectedIds中清除
const clearCompList = (index: number) => {
  if (props.componentConfigurationModel.isModelDisabled) return;
  const compList = props.componentConfigurationModel.siderbarConfig[index].children;
  let updateList: string[] = [];
  const type = compList[0]?.metaclass ? "tree" : "common";
  compList.forEach(comp => {
    updateList.push(comp.id);
  });
  // const list = props.componentConfigurationModel.componentConfig.rightSelectedIds.filter(item => !updateList.includes(item));
  props.componentConfigurationModel.siderbarConfig[index].children = [];
  // props.componentConfigurationModel.componentConfig.rightSelectedIds = [...list];
  props.treeSelectModel.updateNodeDiabled(updateList, type);
  currentIndex.value = -1;
};

// 删除某个分组，也需要讲该分组下在rightSelectedIds中清除
const deleteGroup = (index: number) => {
  if (props.componentConfigurationModel.isModelDisabled) return;
  const compList = props.componentConfigurationModel.siderbarConfig[index].children;
  let updateList: string[] = [];
  const type = compList[0]?.metaclass ? "tree" : "common";
  compList.forEach(comp => {
    updateList.push(comp.id);
  });
  props.componentConfigurationModel.siderbarConfig.splice(index, 1);
  props.treeSelectModel.updateNodeDiabled(updateList, type);
  currentIndex.value = -1;
  currentParentIndex.value = -1;
  if (props.componentConfigurationModel.selectGroupIndex === index) {
    //  删除选中的分组
    props.componentConfigurationModel.selectGroupIndex = -1;
  }
  if (props.componentConfigurationModel.selectGroupIndex > index) {
    //  删除的分组是选中的上方，选中的角标-1
    props.componentConfigurationModel.selectGroupIndex -= 1;
  }
};

// 删除某个组件
const removeComp = (parentIndex, index, comp) => {
  const type = comp.metaclass ? "tree" : "common";
  props.componentConfigurationModel.siderbarConfig[parentIndex].children.splice(index, 1);
  props.treeSelectModel.updateNodeDiabled([comp.id], type);
  currentIndex.value = -1;
};

// 选择分组
const changeSelectGrouop = (index: number) => {
  props.componentConfigurationModel.selectGroupIndex = index;
};

const handleMousedown = e => {
  if (e.target && e.target.className && !e.target.className.includes("comp-item")) {
    currentIndex.value = -1;
  }
};

onMounted(() => {
  window.addEventListener("click", handleMousedown);
});
onUnmounted(() => {
  window.removeEventListener("click", handleMousedown);
});
</script>

<style lang="scss">
@import "@/assets/css/theme.scss";
.v-configuration-comps-right-area {
  width: 310px;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #e4e4e4;
  border-top: 1px solid #e4e4e4;
  border-right: 1px solid #e4e4e4;
  .add-group {
    width: 100%;
    height: 40px;
    padding: 0 8px;
    box-sizing: border-box;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 14px;
    background-color: $frame-siderbar-bg-color;
    cursor: pointer;
    border-bottom: 1px solid #e4e4e4;
  }
  .group-list-wrap {
    display: flex;
    flex: 1;
    flex-direction: column;
    overflow: auto;
    padding-bottom: 16px;
    .group-item {
      display: flex;
      flex-direction: column;
      border-top: 1px solid #e4e4e4;
      border-right: 1px solid #e4e4e4;
      box-shadow: 0px 6px 14px 0px rgba(0, 0, 0, 0.08);
      margin-bottom: 16px;
      .group-item-header {
        height: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 8px;
        border-bottom: 1px solid #e4e4e4;
        .header-left {
          display: flex;
          align-items: center;
          .el-input__wrapper {
            box-shadow: none;
          }
        }
        .header-right {
          display: flex;
          align-items: center;
          ._clear-icon {
            filter: contrast(0) brightness(0.3);
          }
        }
      }
      .group-item-children {
        min-height: 60px;
        display: flex;
        flex-direction: column;
        padding: 8px 0;
        // flex-wrap: wrap;

        .comp-item {
          position: relative;
          height: 24px;
          margin: 0 12px;
          padding: 0 4px;
          box-sizing: border-box;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          cursor: pointer;
          .delete-icon {
            position: absolute;
            top: -6px;
            right: -6px;
            width: 14px;
            height: 14px;
          }
          /*    .comp-item-box {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          } */
          .comp-item-img {
            width: 16px;
            height: 16px;
          }
          .comp-item-label {
            margin-left: 4px;
            font-size: 11px;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        .active {
          border: 1px solid $theme-color;
        }
      }
    }
    .active {
      border: 1px solid $theme-color;
    }
    // &::-webkit-scrollbar {
    //   display: none; /* Chrome Safari */
    // }
  }
  .operation-disabled {
    cursor: not-allowed;
  }
}
</style>
